<template>
  <view class="repair-task">
    <!-- 搜索框 -->
    <!-- <view class="search-box">
      <input type="text" v-model="searchText" placeholder="输入需要搜索的内容" class="search-input" />
      <text class="search-icon">🔍</text>
    </view> -->

    <!-- 筛选条件 -->
    <view class="filter-bar">
      <view class="filter-item">
		  	<text @click="fh()">返回</text>
        <text>共{{total}}条</text>
      </view>
      <view class="filter-item">
        <text>状态</text>
        <picker @change="onStatusChange" :value="statusIndex" :range="statusOptions">
          <view class="dropdown">{{statusOptions[statusIndex]}}</view>
        </picker>
      </view>
   <!--   <view class="filter-item">
        <text>维修方式</text>
        <picker @change="onRepairTypeChange" :value="repairTypeIndex" :range="repairTypeOptions">
          <view class="dropdown">{{repairTypeOptions[repairTypeIndex]}}</view>
        </picker>
      </view> -->
	  <!-- 我的店铺 -->
	  <button 
      style="width:300rpx;height: 70rpx; background-color: #007aff; color:#fff; text-align: center;"
      @click="getShopTaskList"
    >
      我的
    </button>
	<!-- ：{{ merchantName }} -->
  <!--    <view class="filter-item">
        <text>日期</text>
        <picker 
          mode="date" 
          :value="selectedDate"
          @change="onDateChange"
          :start="startDate"
          :end="endDate"
        >
          <view class="dropdown">{{selectedDate || '选择'}}</view>
        </picker>
      </view> -->
    </view>

    <!-- 维修任务列表 -->
    <view class="task-list">
      <view v-for="(task, index) in taskList" :key="task.id" class="task-item">
        <view class="task-header">
          <text class="task-id">维修单号: {{task.id}}</text>
          <text class="completed" v-if="task.status===0">
            已预约
          </text>
		  <text class="progress" v-if="task.status===1">
		    进行中
		  </text>
		  <text class="yj" v-if="task.status===2">
		    已完成
		  </text>
        </view>
        <view class="task-info">
          <view class="info-row">
            <text class="label">订单编号：</text>
            <text class="value">{{task.id}}</text>
          </view>
       <!--   <view class="info-row">
            <text class="label">车牌号：</text>
            <text class="value">{{task.carNum}}</text>
          </view> -->
        <!--  <view class="info-row">
            <text class="label">车辆类型ID：</text>
            <text class="value">{{task.carTypeId}}</text>
          </view> -->
          <view class="info-row">
            <text class="label">取车地址：</text>
            <text class="value">{{task.location}}</text>
          </view>
	<!-- 	  <view class="info-row">
		    <text class="label">维修状态：</text>
		    <text class="value">{{task.status}}</text>
		  </view> -->
         <!-- <view class="info-row">
            <text class="label">联系人姓名：</text>
            <text class="value">{{task.name}}</text>
          </view> -->
         <!-- <view class="info-row">
            <text class="label">联系电话：</text>
            <text class="value">{{task.phone}}</text>
          </view> -->
          <view class="info-row">
            <text class="label">预约时间：</text>
            <text class="value">{{task.reservationTime}}</text>
          </view>
          <view class="info-row">
            <text class="label">维修方式：</text>
            <text class="value">{{task.type}}</text>
          </view>
         <!-- <view class="info-row">
            <text class="label">维修部位照片：</text>
            <image v-if="task.repairPhotos" :src="task.repairPhotos" mode="aspectFit" style="width: 100px; height: 100px;" />
          </view> -->
       <!--   <view class="info-row">
            <text class="label">整车照片：</text>
            <image v-if="task.vehiclePhotos" :src="task.vehiclePhotos" mode="aspectFit" style="width: 100px; height: 100px;" />
          </view> -->
        </view>
        <view class="task-footer">
          <button class="detail-btn" @click="viewDetail(task)">查看详情</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import request from '@/pages/util/request.js';
import baseUrl from '@/pages/util/urlConfig.js';

// 响应式状态
const searchText = ref('')
const statusIndex = ref(0)
const repairTypeIndex = ref(0)
const selectedDate = ref('')
const taskList = ref([])
const total = ref(0)
//店铺名
const merchantName = ref('');
// 日期范围
const startDate = computed(() => formatDate(new Date(Date.now() - 24 * 30 * 60 * 60 * 1000)))
const endDate = computed(() => formatDate(new Date(Date.now() + 3 * 30 * 60 * 60 * 1000)))

// 模拟数据选项，实际应从后端获取
const statusOptions = ref(['全部', '已预约', '进行中', '已完成'])
const repairTypeOptions = ref(['定期维修', '上门取车','故障维修','总成互换维修','零件修复','预防性维护','到店维修'])
//定时器
let taskListTimer = null;
// 生命周期钩子 - 页面加载时获取数据
onMounted(() => {
  getTaskList();
  taskListTimer =setInterval(getTaskList,5000);
  const merchantInfo = uni.getStorageSync('VMerchant');
  
    // 打印完整信息（调试用）
    console.log("登录信息", merchantInfo);
  
    // 提取 reserved2 的值并赋给变量
    if (merchantInfo && merchantInfo.reserved2) {
      merchantName.value = merchantInfo.reserved2;
    } else {
      merchantName.value = '未知商户';
    }
  
    // 你可以在这里使用 merchantName 做其他操作
    console.log("商户名称（reserved2）:", merchantName.value);
});
//清除定时
onUnmounted(()=>{
	clearInterval(taskListTimer);
})
// 获取任务列表
const getTaskList = () => {
  request({
    url: baseUrl + '/qxk/reservation/list',
    method: 'GET',
    data: {
      pageNum: 1,
      pageSize: 10
    },
    success: (res) => {
      if (res.data && res.data.code === 200) {
        taskList.value = res.data.rows || []
        total.value = res.data.total || 0,
	console.log("登录信息", uni.getStorageSync('VMerchant'))
      } else {
        console.error('获取任务列表失败:', res)
        uni.showToast({
          title: res.data?.msg || '获取数据失败',
          icon: 'none'
        })
      }
    },
    fail: (err) => {
      console.error('请求失败:', err)
      uni.showToast({
        title: '请求失败',
        icon: 'none'
      })
    }
  });
}

// 方法
const viewDetail = (task) => {
  // 数据完整性校验
  if (!task?.id) {
    uni.showToast({ title: '无效的任务数据', icon: 'error' })
    return
  }
  
  const taskData = encodeURIComponent(JSON.stringify(task))
  uni.navigateTo({
    url: `/pages/index/weixiurenwu/weixiuxiangqing/weixiuxiangqing?taskData=${taskData}`,
    events: {
      acceptDataFromOpener: (data) => {
        console.log('从详情页返回的数据:', data)
      }
    },
    fail: (err) => {
      console.error('跳转失败:', err)
      uni.showToast({
        title: '跳转失败',
        icon: 'none'
      })
    }
  })
}
const fh = () => {
  uni.navigateBack({ 
    delta: 1,
    fail: (err) => {
      console.error('返回失败:', err)
      // 添加备用跳转逻辑
      uni.switchTab({
        url: '/pages/index/index',
        fail: (err) => {
          uni.showToast({ title: '页面不存在', icon: 'error' })
        }
      })
    }
  })
}
const onStatusChange = (e) => {
  statusIndex.value = Number(e.detail.value)
}

const onRepairTypeChange = (e) => {
  repairTypeIndex.value = Number(e.detail.value)
}

const onDateChange = (e) => {
  selectedDate.value = e.detail.value
}

// 工具函数
const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}
// 新增方法，用于根据店铺名获取任务列表
const getShopTaskList = () => {
  if (!merchantName.value) {
    uni.showToast({
      title: '店铺名未获取到',
      icon: 'none'
    });
    return;
  }

  request({
    url: baseUrl + '/qxk/reservation/list',
    method: 'GET',
    data: {
      pageNum: 1,
      pageSize: 10,
      reserved1: merchantName.value
    },
    success: (res) => {
      if (res.data && res.data.code === 200) {
        taskList.value = res.data.rows || [];
        total.value = res.data.total || 0;
      } else {
        console.error('获取店铺任务列表失败:', res);
        uni.showToast({
          title: res.data?.msg || '获取数据失败',
          icon: 'none'
        });
      }
    },
    fail: (err) => {
      console.error('请求失败:', err);
      uni.showToast({
        title: '请求失败',
        icon: 'none'
      });
    }
  });
};
</script>

<style scoped>
.repair-task {
	margin-top: 28rpx;
  padding: 20rpx;
  background: #f0f0f0;
}

.search-box {
  position: relative;
  margin-bottom: 20rpx;
}

.search-input {
  background: #fff;
  border-radius: 30rpx;
  padding: 10rpx 20rpx;
  padding-right: 60rpx;
}

.search-icon {
  position: absolute;
  right: 20rpx;
  top: 50%;
  transform: translateY(-50%);
}
.yj{
	color: #666;
}
.filter-bar {
  display: flex;
  justify-content: space-between;
  padding: 20rpx 0;
  background: #fff;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
}

.filter-item {
  display: flex;
  align-items: center;
}

.dropdown {
  margin-left: 10rpx;
  color: #333;
  padding: 4rpx 20rpx;
  border-radius: 6rpx;
  border: 1px solid #007AFF;
  min-width: 80rpx;
  text-align: center;
}

.task-list {
  margin-top: 20rpx;
}

.task-item {
  background: #fff;
  border-radius: 10rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.1);
}

.task-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15rpx;
}

.task-status {
  padding: 4rpx 12rpx;
  border-radius: 4rpx;
  font-size: 24rpx;
}

.in-progress {
  color: #007AFF;
}

.completed {
  color: #34C759;
}

.info-row {
  display: flex;
  margin-bottom: 10rpx;
}

.label {
  color: #666;
  width: 160rpx;
  font-size: 24rpx;
}

.detail-btn {
  background: #007AFF;
  color: #fff;
  padding: 6rpx 30rpx;
  border-radius: 30rpx;
  font-size: 28rpx;
  margin-top: 10rpx;
}
</style>
